import React, { PureComponent, lazy, Suspense } from 'react'
import { connect } from 'react-redux'
import { createSetPageErrorAction } from '@/redux/actions/pageError'
import Loading from '@/components/Loading'
import SpaceInfo from './info'
import { spaceApi } from '@/api'
import css from './index.module.scss'
const SpacePosts = lazy(() => import('./posts'))
const SpaceVideos = lazy(() => import('./videos'))
const SpacePhotos = lazy(() => import('./photos'))
class Space extends PureComponent {
    postRef = React.createRef()
    
    state = {
        userInfo: null,
        currentTab: 'Posts',
        tabs: [
            {
                id: 1,
                name: '动态',
                component: 'Posts'
            },
            {
                id: 2,
                name: '视频',
                component: 'Videos'
            },
            {
                id: 3,
                name: '相薄',
                component: 'Photos'
            }
        ],
        nextPostId: null,
        posts: [],
        videos: [],
        photos: []
    }

    get userId() {
        const { match: { params: { id } } } = this.props
        return id
    }    

    get currentList() {
        const { currentTab, posts, videos, photos } = this.state
        let list = []
        switch (currentTab) {
            case 'Posts':
                list = posts
                break
            case 'Videos':
                list = videos
                break
            case 'Photos':
                list = photos                
                break
            default:
                list = posts
        }
        return list
    }

    getInfo = async () => {
        try {
            const { data } = await spaceApi.getInfo({
                mid: this.userId
            })
            if (data) {
                this.setState({
                    userInfo: data
                })
            }
        } catch (error) {
            this.props.setPageError(true)
        }
    }

    getPosts =  async () => {
        try {
            const { nextPostId, posts } = this.state
            const { data } = await spaceApi.getUserPosts({
                host_uid: this.userId,
                offset_dynamic_id: nextPostId || ''
            })
            if (data) {
                const { has_more, cards } = data
                if (has_more === 0) {
                    this.setState({
                        nextPostId: -1
                    })
                    this.complete()
                } else {
                    this.setState({
                        nextPostId: cards[cards.length - 1].desc.dynamic_id_str,
                        posts: [...posts, ...cards]
                    })
                }               
            }
        } catch (error) {               
        } finally {
            this.stopLoading()
        }
    }

    getVideos = async () => {
        try {
            const { data } = await spaceApi.getUserVideos({
                mid: this.userId
            })
            if (data) {
                this.setState({
                    videos: data.list.vlist
                })
            }
        } catch (error) {            
        }
    }

    getPhotos = async () => {
        try {
            const { data } = await spaceApi.getUserPhotos({
                uid: this.userId
            })
            if (data) {
                this.setState({
                    photos: data.items
                })
            }
        } catch (error) {           
        }
    }

    handleTab = tab => {
        this.setState({
            currentTab: tab.component
        }, () => {
            if (this.currentList.length === 0) {
                this.lazyLoadTabData()              
            }
        })        
    }

    lazyLoadTabData = () => {
        const { currentTab } = this.state
        switch (currentTab) {
            case 'Posts':            
                this.getPosts()
                break
            case 'Videos':     
                this.getVideos()           
                break
            case 'Photos':   
                this.getPhotos()             
                break
            default:
                this.getPosts()
        }
    }

    complete = () => {
        this.postRef.current?.complete()
    }

    stopLoading = () => {
        this.postRef.current?.stopLoading()
    }

    handlePostLoad = () => {
        const { nextPostId } = this.state
        if (nextPostId === -1) {
            this.complete()
            return
        }
        this.getPosts()
    }

    componentDidMount() {
        this.getInfo()
        this.lazyLoadTabData()
    }

    componentDidUpdate(prevProps) {        
        const prevId = prevProps.match.params.id
        if (prevId !== this.userId) {
            this.getInfo()
            this.setState({
                nextPostId: null,
                posts: [],
                videos: [],
                photos: [],
                currentTab: 'Posts'                
            }, () => {
                this.lazyLoadTabData()
            })            
        }
    }

    render() {        
        const { userInfo, tabs, currentTab } = this.state        
        return (                
            <>
                { 
                    this.userId && userInfo && 
                    <>
                        <SpaceInfo detailData={userInfo} mid={this.userId} />
                        <ul className={css["tabs"]}>
                            {
                                tabs.map(item => {
                                    return (
                                        <li
                                            key={item.id}
                                            className={item.component === currentTab ? 'active' : ''}
                                            onClick={() => this.handleTab(item)}
                                        >
                                            {item.name}
                                        </li>
                                    )
                                })
                            }                        
                        </ul>
                        <Suspense fallback={<Loading/>}>
                            { 
                                currentTab === 'Posts' && 
                                <SpacePosts 
                                    ref={this.postRef}                                        
                                    list={this.currentList} 
                                    onReachEnd={this.handlePostLoad}
                                /> 
                            }
                            { currentTab === 'Videos' && <SpaceVideos list={this.currentList} /> }
                            { currentTab === 'Photos' && <SpacePhotos list={this.currentList} /> }
                        </Suspense>
                    </>
                }                    
            </>
        )               
    }
}

export default connect(
    null,
    {
        setPageError: createSetPageErrorAction
    }
)(Space)